package webapp.mvc.controllers;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.view.RedirectView;
import webapp.mvc.controllers.forms.SimpleResponse;
import webapp.mvc.controllers.forms.UploadFileForm;
import webapp.mvc.oss.IStoreService;
import webapp.mvc.oss.ObjectStoreInfo;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/file")
public class FileController {
    private static final Logger LOG = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private IStoreService storeService;

    /**
     * 可以提供直接form上传和iframe上传回调两种交互方式
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/upload_using_forms", method = RequestMethod.POST)
    public
    @ResponseBody
    String uploadFileUsingForm(@RequestParam("file") CommonsMultipartFile file, UploadFileForm uploadFileForm) {
        String filename = file.getOriginalFilename();
        try {
            ObjectStoreInfo objectStoreInfo = storeService.putFile(file.getInputStream(), filename);
            // 根据交互方式给出不同的返回结果
            if ("form".equals(uploadFileForm.getUploadType())) {
                return JSON.toJSONString(objectStoreInfo);
            } else if ("iframe".equals(uploadFileForm.getUploadType())) {
                return String.format("<script>parent.window.%s(\"%s\");</script>", uploadFileForm.getJsCallback(), objectStoreInfo.getKey());
            } else if ("postMessage".equals(uploadFileForm.getUploadType())) {
                return String.format("<script>parent.postMessage(\"%s('%s')\", \"%s\");</script>", uploadFileForm.getJsCallback(), objectStoreInfo.getKey(), uploadFileForm.getOriginHost());
            } else {
                return JSON.toJSONString(objectStoreInfo);
            }
        } catch (Exception e) {
            LOG.error("upload file error", e);
            return e.getMessage();
        }
    }

    @RequestMapping("/view_direct/{key}")
    public Object viewFileDirect(HttpServletRequest request, @PathVariable String key) {
        try {
            String downloadUrl = storeService.getFile(request, key, key);
            return new RedirectView(downloadUrl);
        } catch (Exception e) {
            return new SimpleResponse(100, e.getMessage());
        }
    }

    @RequestMapping("/view/{key}")
    public SimpleResponse viewFile(HttpServletRequest request, @PathVariable String key) {
        try {
            String downloadUrl = storeService.getFile(request, key, key);
            return new SimpleResponse(SimpleResponse.OK, downloadUrl);
        } catch (Exception e) {
            return new SimpleResponse(100, e.getMessage());
        }
    }
}
